package com.uzai.console.service.tb.tborder.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.enums.OrderReStatusEnum;
import com.uzai.common.enums.OrderSourceEnum;
import com.uzai.common.enums.OrderStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.common.utils.ZipUtils;
import com.uzai.console.component.excel.template.TbRefundOrderExcelDemo;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.feign.tborder.*;
import com.uzai.console.dto.tb.tborder.*;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.entity.*;
import com.uzai.console.enums.ExportInfoTypeEnum;
import com.uzai.console.enums.OrderPullPlatformEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.para.TbOrderRemoteApiPara;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.exportinfo.ExportInfoService;
import com.uzai.console.service.feign.TbOrderFeignService;
import com.uzai.console.service.remoteapi.TbOrderRemoteApiService;
import com.uzai.console.service.tb.tborder.TbOrderSyncService;
import com.uzai.console.vo.exportinfo.ExportAmountVo;
import com.uzai.console.vo.tb.tborder.TbOrderExport;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2019/11/27 11:23
 * @Description:
 */
@Service
public class TbOrderSyncServiceImpl implements TbOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(TbOrderSyncServiceImpl.class);

    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbOrderRemoteApiService tbOrderRemoteApiService;
    @Autowired
    private TbOrderFeignService tbOrderFeignService;
    @Autowired
    private TbTokenApiMapper tbTokenApiMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private ExportInfoService exportInfoService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private OrderPullMapper orderPullMapper;

    /**
     * 手动下载单个淘宝联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDownLoadDto
     * @return null
     */
    @Override
    public void downloadOrder(TbOrderDownLoadDto tbOrderDownLoadDto, Long tbTokenId) {
        //调用订单业务库服务器
        TbToken tbToken = tbTokenMapper.selectById(tbTokenId, tbOrderDownLoadDto.getMerId());
        if (tbToken != null) {
            try{
                TbOrderPullDto tbOrderPullDto = new TbOrderPullDto();
                tbOrderPullDto.setTokenId(String.valueOf(tbToken.getUserId()));
                tbOrderPullDto.setPlatform("tb");
                tbOrderPullDto.setStartTime(tbOrderDownLoadDto.getQueryStartTime());
                tbOrderPullDto.setEndTime(tbOrderDownLoadDto.getQueryEndTime());
                tbOrderPullDto.setTimeType(tbOrderDownLoadDto.getQueryTimeType());
                //请求订单拉取接口
                tbOrderFeignService.pull(tbOrderPullDto);
            }catch (Exception e){
                logger.error(e.getMessage());
            }
        }

        //调用订单拉取库服务器
        //判断是否到期,未到期才调用订单拉取库服务器拉取订单
        if (tbToken != null) {
            //判断联盟是否到期
            if (Tools.getInteger(tbToken.getExptime()).intValue() > DateUtil.getNowTime()) {
                if (tbOrderDownLoadDto.getOrderScene().intValue() != 4) { //不是维权订单
                    TbOrderRemoteApiPara tbOrderRemoteApiPara = new TbOrderRemoteApiPara();
                    tbOrderRemoteApiPara.setAccessToken(tbToken.getAccessToken());
                    tbOrderRemoteApiPara.setUserId(tbToken.getUserId());
                    tbOrderRemoteApiPara.setUserName(tbToken.getUserName());
                    tbOrderRemoteApiPara.setQueryTimeType(tbOrderDownLoadDto.getQueryTimeType());
                    tbOrderRemoteApiPara.setQueryStartTime(tbOrderDownLoadDto.getQueryStartTime());
                    tbOrderRemoteApiPara.setQueryEndTime(tbOrderDownLoadDto.getQueryEndTime());
                    tbOrderRemoteApiPara.setOrderScene(tbOrderDownLoadDto.getOrderScene());
                    tbOrderRemoteApiService.remoteDownload(tbOrderRemoteApiPara);
                } else { //维权订单
                    TbOrderRemoteApiPara tbOrderRemoteApiPara = new TbOrderRemoteApiPara();
                    tbOrderRemoteApiPara.setAccessToken(tbToken.getAccessToken());
                    tbOrderRemoteApiPara.setUserId(tbToken.getUserId());
                    tbOrderRemoteApiPara.setUserName(tbToken.getUserName());
                    tbOrderRemoteApiPara.setQueryTimeType(tbOrderDownLoadDto.getQueryTimeType());
                    tbOrderRemoteApiPara.setQueryStartTime(tbOrderDownLoadDto.getQueryStartTime());
                    tbOrderRemoteApiPara.setQueryEndTime(tbOrderDownLoadDto.getQueryEndTime());
                    tbOrderRemoteApiPara.setOrderScene(tbOrderDownLoadDto.getOrderScene());
                    tbOrderRemoteApiService.remoteDownloadRefund(tbOrderRemoteApiPara);
                }
            }
        }
    }

    /**
     * 手动下载单个淘宝联盟订单(订单不入订单库，直接通过API拉取到业务库)
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDownLoadDto
     * @return null
     */
    @Override
    public void downloadOrder_notInStock(TbOrderDownLoadDto tbOrderDownLoadDto, Long tbTokenId) {
        //调用订单业务库服务器
        TbToken tbToken = tbTokenMapper.selectById(tbTokenId, tbOrderDownLoadDto.getMerId());
        //判断是否到期,未到期才调用订单拉取库服务器拉取订单
        if (tbToken != null) {
            //判断联盟是否到期
            if (Tools.getInteger(tbToken.getExptime()).intValue() > DateUtil.getNowTime()) {
                try {
                    if (tbOrderDownLoadDto.getOrderScene().intValue() != 4) { //不是维权订单
                        List<TimeVO> timeVOList = DateUtil.getTbkOrderTimeScope(tbOrderDownLoadDto.getQueryStartTime(), tbOrderDownLoadDto.getQueryEndTime());
                        if(timeVOList != null && timeVOList.size() > 0){
                            //加入维权订单下载列表当中
                            List<OrderPull> orderPullList = new ArrayList<>();
                            int now = DateUtil.getNowTime();
                            for (TimeVO timeVO : timeVOList){
                                //2023-11-13屏蔽以下同步下载订单代码，淘宝订单下载改成异步模式
//                                TbOrderDownloadDto tbOrderDownloadDto = new TbOrderDownloadDto();
//                                tbOrderDownloadDto.setUserId(tbToken.getUserId());
//                                tbOrderDownloadDto.setAccessToken(tbToken.getAccessToken());
//                                tbOrderDownloadDto.setUserName(tbToken.getUserName());
//                                tbOrderDownloadDto.setBeginTime(timeVO.getBeginTime());
//                                tbOrderDownloadDto.setEndTime(timeVO.getEndTime());
//                                tbOrderDownloadDto.setOrderScene(tbOrderDownLoadDto.getOrderScene());
//                                tbOrderDownloadDto.setQueryType(tbOrderDownLoadDto.getQueryTimeType());
//                                tbOrderDownloadDto.setTurnlink(tbToken.getTurnlink());
//                                //请求订单拉取接口
//                                UzaiRespVo<Boolean> uzaiRespVo = tbOrderFeignService.tbOrderDownload(tbOrderDownloadDto);
//                                logger.info("--手动通过API拉取淘宝订单-para={},result={}", JSONObject.toJSONString(tbOrderDownloadDto),JSONObject.toJSONString(uzaiRespVo));

                                //2023-11-13修改，淘宝订单下载改成异步模式
                                TbOrderDownloadDto tbOrderDownloadDto = new TbOrderDownloadDto();
                                tbOrderDownloadDto.setUserId(tbToken.getUserId());
                                tbOrderDownloadDto.setAccessToken(tbToken.getAccessToken());
                                tbOrderDownloadDto.setUserName(tbToken.getUserName());
                                tbOrderDownloadDto.setBeginTime(timeVO.getBeginTime());
                                tbOrderDownloadDto.setEndTime(timeVO.getEndTime());
                                tbOrderDownloadDto.setOrderScene(tbOrderDownLoadDto.getOrderScene());
                                tbOrderDownloadDto.setQueryType(tbOrderDownLoadDto.getQueryTimeType());
                                tbOrderDownloadDto.setTurnlink(tbToken.getTurnlink());

                                //新建订单拉取对象
                                OrderPull orderPull = new OrderPull();
                                orderPull.setId(IdWorker.getId());
                                orderPull.setMerId(tbToken.getMerId());
                                orderPull.setPlatform(OrderPullPlatformEnum.TB.getKey());
                                orderPull.setType(tbOrderDownloadDto.getQueryType());
                                orderPull.setStartTime(tbOrderDownloadDto.getBeginTime());
                                orderPull.setEndTime(tbOrderDownloadDto.getEndTime());
                                orderPull.setTokenId(tbToken.getId());
                                orderPull.setParaData(JSONObject.toJSONString(tbOrderDownloadDto));
                                orderPull.setCreateTime(now);
                                orderPull.setUpdateTime(now);
                                orderPullList.add(orderPull);

                                //超过500个先入库一次，防止数据过多，保存失败
                                if(orderPullList.size() > 500){
                                    //保存入库
                                    orderPullMapper.batchAdd(orderPullList);
                                    orderPullList.clear();
                                }
                            }

                            //最后在将剩下的入库
                            if(orderPullList.size() > 0){
                                //保存入库
                                orderPullMapper.batchAdd(orderPullList);
                                orderPullList.clear();
                            }
                        }
                    } else { //维权订单
                        List<TimeVO> timeVOList = DateUtil.getTbkOrderRefundTimeScope(tbOrderDownLoadDto.getQueryStartTime(), tbOrderDownLoadDto.getQueryEndTime());
                        if(timeVOList != null && timeVOList.size() > 0){
                            //加入维权订单下载列表当中
                            List<OrderPull> orderPullList = new ArrayList<>();
                            int now = DateUtil.getNowTime();
                            for (TimeVO timeVO : timeVOList){
                                TbOrderRefundDownloadDto tbOrderRefundDownloadDto_channal = new TbOrderRefundDownloadDto();
                                tbOrderRefundDownloadDto_channal.setUserId(tbToken.getUserId());
                                tbOrderRefundDownloadDto_channal.setAccessToken(tbToken.getAccessToken());
                                tbOrderRefundDownloadDto_channal.setUserName(tbToken.getUserName());
                                tbOrderRefundDownloadDto_channal.setBeginTime(timeVO.getBeginTime());
                                tbOrderRefundDownloadDto_channal.setEndTime(timeVO.getEndTime());
                                tbOrderRefundDownloadDto_channal.setBizType(1); //渠道维权订单
                                tbOrderRefundDownloadDto_channal.setQueryType(tbOrderDownLoadDto.getQueryTimeType());
                                tbOrderRefundDownloadDto_channal.setTurnlink(tbToken.getTurnlink());
                                //请求订单拉取接口
                                //UzaiRespVo<Boolean> uzaiRespVo_channal = tbOrderFeignService.tbOrderRefundDownload(tbOrderRefundDownloadDto_channal);
                                //logger.info("--手动通过API拉取淘宝渠道维权订单-para={},result={}", JSONObject.toJSONString(tbOrderRefundDownloadDto_channal),JSONObject.toJSONString(uzaiRespVo_channal));

                                //新建订单拉取对象
                                OrderPull orderPull = new OrderPull();
                                orderPull.setId(IdWorker.getId());
                                orderPull.setMerId(tbToken.getMerId());
                                orderPull.setPlatform(OrderPullPlatformEnum.TBWQ.getKey());
                                orderPull.setType(tbOrderRefundDownloadDto_channal.getQueryType());
                                orderPull.setStartTime(tbOrderRefundDownloadDto_channal.getBeginTime());
                                orderPull.setEndTime(tbOrderRefundDownloadDto_channal.getEndTime());
                                orderPull.setTokenId(tbToken.getId());
                                orderPull.setParaData(JSONObject.toJSONString(tbOrderRefundDownloadDto_channal));
                                orderPull.setCreateTime(now);
                                orderPull.setUpdateTime(now);
                                orderPullList.add(orderPull);

                                //超过500个先入库一次，防止数据过多，保存失败
                                if(orderPullList.size() > 500){
                                    //保存入库
                                    orderPullMapper.batchAdd(orderPullList);
                                    orderPullList.clear();
                                }
                            }

                            //最后在将剩下的入库
                            if(orderPullList.size() > 0){
                                //保存入库
                                orderPullMapper.batchAdd(orderPullList);
                                orderPullList.clear();
                            }
                        }
                    }
                }catch (Exception e){
                    logger.error(e.getMessage());
                }
            }
        }
    }

    /**
     * 通过API手动下载单个淘宝联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderApiDownLoadDto
     * @return null
     */
    @Override
    public void downloadOrderApi(TbOrderApiDownLoadDto tbOrderApiDownLoadDto, Long tbTokenId) {
        //调用订单业务库服务器
        TbTokenApi tbTokenApi = tbTokenApiMapper.selectById(tbTokenId, tbOrderApiDownLoadDto.getMerId());
        //判断是否到期,未到期才调用订单拉取库服务器拉取订单
        if (tbTokenApi != null) {
            //判断联盟是否到期
            if (Tools.getInteger(tbTokenApi.getExptime()).intValue() > DateUtil.getNowTime()) {
                try {
                    if (tbOrderApiDownLoadDto.getOrderScene().intValue() != 4) { //不是维权订单
                        TbOrderDownloadDto tbOrderDownloadDto = new TbOrderDownloadDto();
                        tbOrderDownloadDto.setUserId(tbTokenApi.getUserId());
                        tbOrderDownloadDto.setAccessToken(tbTokenApi.getAccessToken());
                        tbOrderDownloadDto.setUserName(tbTokenApi.getUserName());
                        tbOrderDownloadDto.setBeginTime(tbOrderApiDownLoadDto.getQueryStartTime());
                        tbOrderDownloadDto.setEndTime(tbOrderApiDownLoadDto.getQueryEndTime());
                        tbOrderDownloadDto.setOrderScene(tbOrderApiDownLoadDto.getOrderScene());
                        tbOrderDownloadDto.setQueryType(tbOrderApiDownLoadDto.getQueryTimeType());
                        //请求订单拉取接口
                        UzaiRespVo<Boolean> uzaiRespVo = tbOrderFeignService.tbOrderDownload(tbOrderDownloadDto);

                        logger.info("--手动通过API拉取淘宝订单-para={},result={}", JSONObject.toJSONString(tbOrderDownloadDto),JSONObject.toJSONString(uzaiRespVo));

                    } else {
                        TbOrderRefundDownloadDto tbOrderRefundDownloadDto_channal = new TbOrderRefundDownloadDto();
                        tbOrderRefundDownloadDto_channal.setUserId(tbTokenApi.getUserId());
                        tbOrderRefundDownloadDto_channal.setAccessToken(tbTokenApi.getAccessToken());
                        tbOrderRefundDownloadDto_channal.setUserName(tbTokenApi.getUserName());
                        tbOrderRefundDownloadDto_channal.setBeginTime(tbOrderApiDownLoadDto.getQueryStartTime());
                        tbOrderRefundDownloadDto_channal.setEndTime(tbOrderApiDownLoadDto.getQueryEndTime());
                        tbOrderRefundDownloadDto_channal.setBizType(1); //渠道维权订单
                        tbOrderRefundDownloadDto_channal.setQueryType(tbOrderApiDownLoadDto.getQueryTimeType());
                        //请求订单拉取接口
                        UzaiRespVo<Boolean> uzaiRespVo_channal = tbOrderFeignService.tbOrderRefundDownload(tbOrderRefundDownloadDto_channal);

                        logger.info("--手动通过API拉取淘宝渠道维权订单-para={},result={}", JSONObject.toJSONString(tbOrderRefundDownloadDto_channal),JSONObject.toJSONString(uzaiRespVo_channal));

//                        TbOrderRefundDownloadDto tbOrderRefundDownloadDto_relation = new TbOrderRefundDownloadDto();
//                        tbOrderRefundDownloadDto_relation.setUserId(tbTokenApi.getUserId());
//                        tbOrderRefundDownloadDto_relation.setAccessToken(tbTokenApi.getAccessToken());
//                        tbOrderRefundDownloadDto_relation.setUserName(tbTokenApi.getUserName());
//                        tbOrderRefundDownloadDto_relation.setBeginTime(tbOrderApiDownLoadDto.getQueryStartTime());
//                        tbOrderRefundDownloadDto_relation.setEndTime(tbOrderApiDownLoadDto.getQueryEndTime());
//                        tbOrderRefundDownloadDto_relation.setBizType(2); //会员维权订单
//                        tbOrderRefundDownloadDto_relation.setQueryType(tbOrderApiDownLoadDto.getQueryTimeType());
//                        //请求订单拉取接口
//                        UzaiRespVo<Boolean> uzaiRespVo_relation = tbOrderFeignService.tbOrderRefundDownload(tbOrderRefundDownloadDto_relation);
//
//                        logger.info("--手动通过API拉取淘宝会员维权订单-para={},result={}", JSONObject.toJSONString(tbOrderRefundDownloadDto_relation),JSONObject.toJSONString(tbOrderRefundDownloadDto_relation));

                    }
                }catch (Exception e){
                    logger.error(e.getMessage());
                }
            }
        }
    }

    /**
     * 异步手动下载多个淘宝联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDownLoadDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void downloadOrderListSync(TbOrderDownLoadDto tbOrderDownLoadDto) {
        if(tbOrderDownLoadDto.getIdList() != null && tbOrderDownLoadDto.getIdList().size() > 0){
            for (Long id : tbOrderDownLoadDto.getIdList()){
                try {
                    downloadOrder(tbOrderDownLoadDto, id);
                }catch (Exception e){
                    logger.error("-------downloadOrderListSync is error tbTokenId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 异步手动下载多个淘宝联盟订单-订单不入库订单库，直接通过API接口拉取订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDownLoadDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void downloadOrderListSync_notInStock(TbOrderDownLoadDto tbOrderDownLoadDto) {
        if(tbOrderDownLoadDto.getIdList() != null && tbOrderDownLoadDto.getIdList().size() > 0){
            for (Long id : tbOrderDownLoadDto.getIdList()){
                try {
                    downloadOrder_notInStock(tbOrderDownLoadDto, id);
                }catch (Exception e){
                    logger.error("-------downloadOrderListSync is error tbTokenId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 通过API手动下载所有淘宝联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderDownLoadByApiDto
     * @return null
     */
    @Async("taskExecutor")
    public void downloadOrderApiListSync (TbOrderApiDownLoadDto tbOrderDownLoadByApiDto){
        if(tbOrderDownLoadByApiDto.getIdList() != null && tbOrderDownLoadByApiDto.getIdList().size() > 0){
            for (Long id : tbOrderDownLoadByApiDto.getIdList()){
                try {
                    downloadOrderApi(tbOrderDownLoadByApiDto, id);
                }catch (Exception e){
                    logger.error("-------downloadOrderApiListSync is error tbTokenId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 远程调用订单库API，手动更新单个订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrder
     * @return null
     */
    @Override
    public void updateTbOrder(TbOrder tbOrder) {
        //判断订单存在或者已删除
        if(tbOrder == null){
            return;
        }

        if(tbOrder.getAlimmTbId() != null){
            TbToken tbToken = null;
            if(uzaiConsoleSysConfig.getTbAppkeyDg().equals(tbOrder.getAppKey())){
                tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbOrder.getAlimmTbId(), 1);
            }else{
                tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbOrder.getAlimmTbId(), 0);
            }
            if(tbToken != null){
                //订单调用订单库拉取更新
                TbOrderRemoteApiPara tbOrderRemoteApiPara = new TbOrderRemoteApiPara();
                tbOrderRemoteApiPara.setAccessToken(tbToken.getAccessToken());
                tbOrderRemoteApiPara.setUserId(tbToken.getUserId());
                tbOrderRemoteApiPara.setUserName(tbToken.getUserName());
                tbOrderRemoteApiPara.setQueryTimeType(1); //创建时间
                tbOrderRemoteApiPara.setQueryStartTime(tbOrder.getCreatedt() -30);
                tbOrderRemoteApiPara.setQueryEndTime(tbOrder.getCreatedt() + 30);
                tbOrderRemoteApiPara.setParentOrderNo(tbOrder.getParentOrderNo());//父订单号
                tbOrderRemoteApiPara.setChildOrderNo(tbOrder.getChildOrderNo()); //子订单号
                tbOrderRemoteApiPara.setTurnlink(tbToken.getTurnlink());  //转链类型
                if(tbOrder.getRelationId() != null){
                    tbOrderRemoteApiPara.setOrderScene(2); //渠道订单
                }else if(tbOrder.getSpecialId() != null){
                    tbOrderRemoteApiPara.setOrderScene(3); //会员订单
                }else{
                    tbOrderRemoteApiPara.setOrderScene(1); //常规订单
                }
                tbOrderRemoteApiService.remoteDownload(tbOrderRemoteApiPara);

                //调用订单库远程拉取淘宝维权订单
                TbOrderRemoteApiPara tbOrderRemoteApiPara_refund = new TbOrderRemoteApiPara();
                tbOrderRemoteApiPara_refund.setAccessToken(tbToken.getAccessToken());
                tbOrderRemoteApiPara_refund.setUserId(tbToken.getUserId());
                tbOrderRemoteApiPara_refund.setUserName(tbToken.getUserName());
                tbOrderRemoteApiPara_refund.setQueryTimeType(4); //订单创建时间
                tbOrderRemoteApiPara_refund.setQueryStartTime(tbOrder.getCreatedt() -30);
                tbOrderRemoteApiPara_refund.setQueryEndTime(tbOrder.getCreatedt() + 30);
                tbOrderRemoteApiPara_refund.setOrderScene(4);
                tbOrderRemoteApiPara_refund.setTurnlink(tbToken.getTurnlink());  //转链类型
                tbOrderRemoteApiService.remoteDownloadRefund(tbOrderRemoteApiPara_refund);
            }
        }
    }

    /**
     * 远程调用订单库API，更新7天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void updateTbOrderUnReceivedListSync(Long merId) {

        //查询7天前未收货订单
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        tbFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为7天前
        tbFindUnReceicedDto.setQueryEndTime(now-604800);
        //查询付款状态订单（未收货）
        tbFindUnReceicedDto.setStatus(0);

        List<TbOrder> tbOrderList =  tbOrderMapper.findUnReceivedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    updateTbOrder(tbOrder);
                }catch (Exception e){
                    logger.error("-------updateTbOrderUnReceivedList is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @return null
     */
    @Override
    public void updateTbOrderUnReceivedListSync(Long merId, int day) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        tbFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        tbFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（未收货）
        tbFindUnReceicedDto.setStatus(0);
        List<TbOrder> tbOrderList =  tbOrderMapper.findUnReceivedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    updateTbOrder(tbOrder);
                }catch (Exception e){
                    logger.error("-------updateTbOrderUnReceivedListSync is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @param endTime
     * @return null
     */
    public void updateTbOrderUnReceivedListSync(Long merId, Integer startTime, Integer endTime, Long userId){
        if(merId == null){
            return;
        }
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        tbFindUnReceicedDto.setQueryStartTime(startTime);
        tbFindUnReceicedDto.setQueryEndTime(endTime);
        tbFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        tbFindUnReceicedDto.setStatus(0);
        List<TbOrder> tbOrderList =  tbOrderMapper.findUnReceivedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    updateTbOrder(tbOrder);
                }catch (Exception e){
                    logger.error("-------updateTbOrderUnReceivedListSync is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 直接结算，更新day天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @param endTime
     * @return null
     */
    public void updateTbOrderUnReceivedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId){
        if(merId == null){
            return;
        }
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        tbFindUnReceicedDto.setQueryStartTime(startTime);
        tbFindUnReceicedDto.setQueryEndTime(endTime);
        tbFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        tbFindUnReceicedDto.setStatus(0);
        List<TbOrder> tbOrderList =  tbOrderMapper.findUnReceivedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    //订单状态为0-付款状态时，才能确认收货
                    if(tbOrder.getStatus() == 0){
                        //调用确认收货接口
                        TbOrderSettledDto tbOrderSettledDto = new TbOrderSettledDto();
                        tbOrderSettledDto.setMerId(tbOrder.getMerId());
                        tbOrderSettledDto.setOrderId(tbOrder.getParentOrderNo());
                        tbOrderSettledDto.setChildOrderId(tbOrder.getChildOrderNo());
                        UzaiRespVo<Object> result =  tbOrderFeignService.settled(tbOrderSettledDto);
                        logger.info("---发送修改淘宝订单确认收货-para={}, result={}", JSONObject.toJSONString(tbOrderSettledDto), JSONObject.toJSONString(result));
                    }
                }catch (Exception e){
                    logger.error("-------updateTbOrderUnReceivedListSync_settle is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前已冻结的订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @return null
     */
    @Override
    public void updateTbOrderFreezedListSync(Long merId, int day) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        tbFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        tbFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（已收货）
        tbFindUnReceicedDto.setStatus(1);
        List<TbOrder> tbOrderList =  tbOrderMapper.findFreezedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    updateTbOrder(tbOrder);
                }catch (Exception e){
                    logger.error("-------updateTbOrderUnReceivedListSync is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }


    /**
     * 远程调用订单库API，更新day天前订单-已冻结
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    public void updateTbOrderFreezedListSync(Long merId, Integer startTime, Integer endTime, Long userId){
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        tbFindUnReceicedDto.setQueryStartTime(startTime);
        tbFindUnReceicedDto.setQueryEndTime(endTime);
        tbFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        tbFindUnReceicedDto.setStatus(1);
        List<TbOrder> tbOrderList =  tbOrderMapper.findFreezedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    updateTbOrder(tbOrder);
                }catch (Exception e){
                    logger.error("-------updateTbOrderUnReceivedListSync is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前冻结订单-直接结算
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @param endTime
     * @return null
     */
    public void updateTbOrderFreezedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId){
        if(merId == null){
            return;
        }
        //查询冻结的订单
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        tbFindUnReceicedDto.setQueryStartTime(startTime);
        tbFindUnReceicedDto.setQueryEndTime(endTime);
        tbFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        tbFindUnReceicedDto.setStatus(1);
        List<TbOrder> tbOrderList =  tbOrderMapper.findFreezedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    //先将订单状态修改为0-付款状态时，才能确认收货
                    tbOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    tbOrderMapper.updateStatus(tbOrder);
                    //调用确认收货接口
                    TbOrderSettledDto tbOrderSettledDto = new TbOrderSettledDto();
                    tbOrderSettledDto.setMerId(tbOrder.getMerId());
                    tbOrderSettledDto.setOrderId(tbOrder.getParentOrderNo());
                    tbOrderSettledDto.setChildOrderId(tbOrder.getChildOrderNo());
                    UzaiRespVo<Object> result =  tbOrderFeignService.settled(tbOrderSettledDto);
                    logger.info("---发送修改淘宝订单确认收货-para={}, result={}", JSONObject.toJSONString(tbOrderSettledDto), JSONObject.toJSONString(result));
                }catch (Exception e){
                    logger.error("-------updateTbOrderFreezedListSync_settle is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前维权中订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @return null
     */
    public void updateTbOrderRefundingListSync(Long merId, int day) {
        if(merId == null){
            return;
        }
        //查询7天维权中订单
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        tbFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        tbFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（维权中）
        tbFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<TbOrder> tbOrderList =  tbOrderMapper.findUnReceivedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    updateTbOrder(tbOrder);
                }catch (Exception e){
                    logger.error("-------updateTbOrderUnReceivedListSync is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }


    /**
     * 远程调用订单库API，更新维权中的订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @param endTime
     * @return null
     */
    public void updateTbOrderRefundingListSync(Long merId, Integer startTime, Integer endTime, Long userId){
        if(merId == null){
            return;
        }
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        tbFindUnReceicedDto.setQueryStartTime(startTime);
        tbFindUnReceicedDto.setQueryEndTime(endTime);
        tbFindUnReceicedDto.setUserId(userId);
        //根据订单状态查询
        tbFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<TbOrder> tbOrderList =  tbOrderMapper.findUnReceivedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    updateTbOrder(tbOrder);
                }catch (Exception e){
                    logger.error("-------updateTbOrdeRefundingListSync is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新维权中订单-直接结算
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @param endTime
     * @return null
     */
    public void updateTbOrderRefundingListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId){
        if(merId == null){
            return;
        }
        TbFindUnReceicedDto tbFindUnReceicedDto = new TbFindUnReceicedDto();
        tbFindUnReceicedDto.setMerId(merId);
        tbFindUnReceicedDto.setQueryStartTime(startTime);
        tbFindUnReceicedDto.setQueryEndTime(endTime);
        tbFindUnReceicedDto.setUserId(userId);
        //根据订单状态查询
        tbFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        //根据订单状态查询
        tbFindUnReceicedDto.setReStatusList(Lists.newArrayList(OrderReStatusEnum.RE_STATUS_NO_VALUE, OrderReStatusEnum.RE_STATUS_FROZEN_VALUE));
        List<TbOrder> tbOrderList =  tbOrderMapper.findUnReceivedList(tbFindUnReceicedDto);
        if(tbOrderList != null){
            for (TbOrder tbOrder : tbOrderList){
                try {
                    //先将订单状态修改为0-付款状态时，才能确认收货
                    tbOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    tbOrderMapper.updateStatus(tbOrder);
                    //调用确认收货接口
                    TbOrderSettledDto tbOrderSettledDto = new TbOrderSettledDto();
                    tbOrderSettledDto.setMerId(tbOrder.getMerId());
                    tbOrderSettledDto.setOrderId(tbOrder.getParentOrderNo());
                    tbOrderSettledDto.setChildOrderId(tbOrder.getChildOrderNo());
                    UzaiRespVo<Object> result =  tbOrderFeignService.settled(tbOrderSettledDto);
                    logger.info("---发送修改淘宝订单确认收货-para={}, result={}", JSONObject.toJSONString(tbOrderSettledDto), JSONObject.toJSONString(result));
                }catch (Exception e){
                    logger.error("-------updateTbOrderRefundingListSync_settle is error ordersn={}, error={}", tbOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 异步上传淘宝维权订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbRefundOrderExcelDemoList
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void uploadTbRefundOrderSync (List<TbRefundOrderExcelDemo> tbRefundOrderExcelDemoList){
        if(tbRefundOrderExcelDemoList != null && tbRefundOrderExcelDemoList.size() > 0){
            for (TbRefundOrderExcelDemo tbRefundOrderExcelDemo : tbRefundOrderExcelDemoList){
                try {
                    TbRefundOrderUploadDto tbRefundOrderUploadDto = new TbRefundOrderUploadDto();

                    //维权发起时间
                    String refundCreateTime = tbRefundOrderExcelDemo.getRefundCreateTime();
                    if(StringUtils.isNotBlank(refundCreateTime)){
                        Integer tkRefundTime = DateUtil.getStrTime(refundCreateTime);
                        tbRefundOrderUploadDto.setTkRefundTime(tkRefundTime);
                    }
                    //维权完成时间
                    String refundFinishTime = tbRefundOrderExcelDemo.getRefundFinishTime();
                    if(StringUtils.isNotBlank(refundFinishTime)){
                        Integer tkRefundSuitTime = DateUtil.getStrTime(refundFinishTime);
                        tbRefundOrderUploadDto.setTkRefundSuitTime(tkRefundSuitTime);
                    }

                    //订单结算时间
                    String accountdt = tbRefundOrderExcelDemo.getAccountdt();
                    if(StringUtils.isNotBlank(accountdt)){
                        Integer earningTime = DateUtil.getStrTime(accountdt);
                        tbRefundOrderUploadDto.setEarningTime(earningTime);
                    }

                    //商品名称
                    tbRefundOrderUploadDto.setTbAuctionTitle(tbRefundOrderExcelDemo.getTitle());
                    //淘宝父订单编号
                    tbRefundOrderUploadDto.setTbTradeParentId(tbRefundOrderExcelDemo.getParentOrderNo());
                    //淘宝子订单编号
                    tbRefundOrderUploadDto.setTbTradeId(tbRefundOrderExcelDemo.getChildOrderNo());
                    //维权状态
                    String refundStatusName = Tools.getStr(tbRefundOrderExcelDemo.getRefundStatusName());
                    if(StringUtils.isNotBlank(refundStatusName)){
                        if(refundStatusName.equals("维权成功")){
                            tbRefundOrderUploadDto.setRefundStatus(2);//维权成功
                        }else if(refundStatusName.equals("维权创建")){
                            tbRefundOrderUploadDto.setRefundStatus(4);//维权创建
                        }else{
                            tbRefundOrderUploadDto.setRefundStatus(3);//维权失败
                        }
                    }

                    //结算金额
                    Double payment = Tools.getDouble(tbRefundOrderExcelDemo.getPayment());
                    tbRefundOrderUploadDto.setTbTradeFinishPrice((int)com.uzai.common.utils.Math.mul(payment,100));
                    //维权退款金额
                    Double refundAmount = Tools.getDouble(tbRefundOrderExcelDemo.getRefundAmount());
                    tbRefundOrderUploadDto.setRefundFee((int)com.uzai.common.utils.Math.mul(refundAmount,100));
                    //推广者身份
                    String orderRole = Tools.getStr(tbRefundOrderExcelDemo.getOrderRole());
                    Double refundOpeAmount = Tools.getDouble(tbRefundOrderExcelDemo.getRefundOpeAmount());
                    if(StringUtils.isNotBlank(orderRole)){
                        if("二方".equals(orderRole)){
                            tbRefundOrderUploadDto.setRefundType(1); //二方
                            tbRefundOrderUploadDto.setTkPubShowReturnFee((int)com.uzai.common.utils.Math.mul(refundOpeAmount,100));
                        }else if("三方".equals(orderRole)){
                            tbRefundOrderUploadDto.setRefundType(2); //三方
                            tbRefundOrderUploadDto.setTk3rdPubShowReturnFee((int)com.uzai.common.utils.Math.mul(refundOpeAmount,100));
                        }
                    }

                    //口碑父订单号
                    tbRefundOrderUploadDto.setAlscPid(tbRefundOrderExcelDemo.getKbParentOrderNo());
                    //口碑子订单号
                    tbRefundOrderUploadDto.setAlscId(tbRefundOrderExcelDemo.getKbChildOrderNo());
                    //请求订单拉取接口
                    UzaiRespVo uzaiRespVo = tbOrderFeignService.refundorderUpload(tbRefundOrderUploadDto);

                    logger.info("---调用上传淘宝维权订单--para={}, result={}", JSONObject.toJSONString(tbRefundOrderUploadDto), JSONObject.toJSONString(uzaiRespVo));


                }catch (Exception e){
                    logger.error("------uploadTbRefundOrderSync-- error={}",e.getMessage());
                }
            }
        }
    }

    /**
     * 修改淘宝未收货订单为已结算(只改订单状态)
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @param status 订单修改之后的状态（2-失效；1-结算）
     * @return null
     */
    public void uploadTbOrderSettingSync(Long merId, int day, int status) {
        if (merId == null) {
            return;
        }
        //设置结束时间为day天前
        int endTime = DateUtil.getNowTime() - day * 24 * 3600;
        tbOrderMapper.updateStatusPayCompleteToSettle(null, endTime, null, merId, status, null);
    }

    @Override
    public void uploadTbOrderSettingSync(Long merId, int day, int status, List<Integer> sourceStatus) {
        if (merId == null) {
            return;
        }
        //设置结束时间为day天前
        int endTime = DateUtil.getNowTime() - day * 24 * 3600;
        tbOrderMapper.updateStatusPayCompleteToSettle(null, endTime, null, merId, status, sourceStatus);
    }

    /**
     * 淘宝订单查询结果导出文件前检验接口
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param tbOrderQuery
     */
    public ExportAmountVo getExportAmount(TbOrderQuery tbOrderQuery){
        //执行分页查询对象
        Page<TbOrder> page = new Page<>();
        tbOrderQuery.convert(page);
        List<TbOrder> tbOrderList =  tbOrderMapper.findByList(page, tbOrderQuery);
        if(tbOrderList == null || tbOrderList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询结果记录数为0");
        }
        //查询总数
        long totalCount = page.getTotal();
        if(totalCount == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询结果记录数为0");
        }

        String price = sysConfigMapper.selectByKey("export_record_price");

        //计算本次导出费用
        double amountTotal = 0.00D;
        if(amountTotal <= 10000){ //少于1万条，只收取1元
            amountTotal = 1.00D;
        }else{//总导出数大于1万条，则根据单价来计算，超过1万条的按照100条的单价费用来计算
            amountTotal = com.uzai.common.utils.Math.add(1.0D, ((totalCount - 10000)/100 + 1) * Double.parseDouble(price));
        }
        ExportAmountVo  exportAmountVo = new ExportAmountVo();
        exportAmountVo.setAmountTotal(amountTotal);
        exportAmountVo.setCountTotal(totalCount);
        exportAmountVo.setPrice(Double.parseDouble(price));

        return exportAmountVo;
    }

    /**
     * 异步下载淘宝订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbOrderExportResultDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void exportTbOrderSync (TbOrderExportResultDto tbOrderExportResultDto){
        //页面查询条件
        TbOrderQuery tbOrderQuery = tbOrderExportResultDto.getTbOrderQuery();
        tbOrderQuery.setMerId(tbOrderExportResultDto.getMerId());

        //计算费用
        ExportAmountVo exportAmountVo = getExportAmount(tbOrderQuery);

        //生成ZIP文件流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(outputStream);

        //每个excel表格订单最大数为10000条
        int exportExcelMaxNum = Const.ExprotFile.EXPORT_EXCEL_MAX_NUM;
        //导出excel文件序号
        int exportFileNumber = 0;

        //分页查询（每页1000条）
        //执行分页查询对象
        Page<TbOrder> page = new Page<>();
        page.setCurrent(1); //只查第一页
        page.setSize(10); //每页查询100个
        page.addOrder(OrderItem.asc("id"));//默认id升序
        Long idStart = 0L;

        //存放导出文件对象(一万条一个表格)
        List<TbOrderExport> tbOrderExportList = new ArrayList<>();

        ArrayList<TbOrder> tbOrderList =  tbOrderMapper.findByList(page, tbOrderQuery);
        while (tbOrderList != null && tbOrderList.size() > 0) {
            for (TbOrder tbOrder : tbOrderList) {
                if (tbOrder.getId().longValue() > idStart.longValue()) {
                    idStart = tbOrder.getId();
                }
                TbOrderExport tbOrderExport = new TbOrderExport();
                BeanUtils.copyProperties(tbOrder, tbOrderExport);

                //订单状态
                if(tbOrder.getStatus() != null){
                    OrderStatusEnum orderStatusEnum = OrderStatusEnum.getById(tbOrder.getStatus());
                    if(orderStatusEnum != null){
                        tbOrderExport.setStatusName(orderStatusEnum.getDesc());
                    }
                }

                //查询机器人信息
                if(tbOrder.getDeviceUniqueId() != null){
                    Device device = deviceService.findDeviceInfoByDeviceUniqueId(tbOrder.getDeviceUniqueId(), tbOrder.getDeviceType(), tbOrder.getMerId());
                    if(device != null){
                        tbOrderExport.setDeviceName(device.getDeviceName());
                    }
                }

                //通过联盟alimmId查询联盟信息，得到联盟账号名称
                if(tbOrder.getAlimmTbId() != null ){
                    TbToken tbToken = null;
                    if(uzaiConsoleSysConfig.getTbAppkeyDg().equals(tbOrder.getAppKey())){
                        tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbOrder.getAlimmTbId(), 1);
                    }else{
                        tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbOrder.getAlimmTbId(), 0);
                    }
                    if(tbToken != null){
                        tbOrderExport.setAlimmName(tbToken.getUserName());
                    }
                }

                //返利状态
                if(tbOrder.getReStatus() != null){
                    OrderReStatusEnum orderReStatusEnum = OrderReStatusEnum.getById(tbOrder.getReStatus());
                    if(orderReStatusEnum != null){
                        tbOrderExport.setReStatusName(orderReStatusEnum.getDesc());
                    }
                }

                //订单来源
                if(tbOrder.getOrderSource() != null){
                    OrderSourceEnum orderSourceEnum = OrderSourceEnum.getById(tbOrder.getOrderSource());
                    if(orderSourceEnum != null){
                        tbOrderExport.setOrderSourceName(orderSourceEnum.getDesc());
                    }
                }

                //创建时间
                if(tbOrder.getCreatedt() != null && tbOrder.getCreatedt().intValue() != 0){
                    tbOrderExport.setCreatedtStr(Tools.getDateFormat(new Date(tbOrder.getCreatedt() * 1000L), "yyyy-MM-dd HH:mm:ss"));
                }
                //付款时间
                if(tbOrder.getPaydt() != null && tbOrder.getPaydt().intValue() != 0){
                    tbOrderExport.setPaydStr(Tools.getDateFormat(new Date(tbOrder.getPaydt() * 1000L), "yyyy-MM-dd HH:mm:ss"));
                }
                //结算时间
                if(tbOrder.getAccountdt() != null && tbOrder.getAccountdt().intValue() != 0){
                    tbOrderExport.setAccountdtStr(Tools.getDateFormat(new Date(tbOrder.getAccountdt() * 1000L), "yyyy-MM-dd HH:mm:ss"));
                }
                //维权开始时间
                if(tbOrder.getRefundCreateTime() != null && tbOrder.getRefundCreateTime().intValue() != 0){
                    tbOrderExport.setRefundCreateTimeStr(Tools.getDateFormat(new Date(tbOrder.getRefundCreateTime() * 1000L), "yyyy-MM-dd HH:mm:ss"));
                }
                //维权结束时间
                if(tbOrder.getRefundFinishTime() != null && tbOrder.getRefundFinishTime().intValue() != 0){
                    tbOrderExport.setRefundFinishTimeStr(Tools.getDateFormat(new Date(tbOrder.getRefundFinishTime() * 1000L), "yyyy-MM-dd HH:mm:ss"));
                }

                //是否免单
                if(Tools.getInteger(tbOrder.getFree()).intValue() == 1){
                    tbOrderExport.setFreeName("是");
                }else{
                    tbOrderExport.setFreeName("否");
                }

                tbOrderExportList.add(tbOrderExport);

                //判断条数，如果条数大于10000条，生成excel文件
                if(tbOrderExportList.size() >= exportExcelMaxNum){
                    ByteArrayOutputStream byteArrayOutputStream = null;
                    try {
                        //导出的文件序号,每次导出+1
                        exportFileNumber ++ ;
                        String fileName = "淘宝订单_" + exportFileNumber +".xlsx";
                        //创建流
                        byteArrayOutputStream = new ByteArrayOutputStream();
                        //打包成ZIP文件
                        EasyExcel.write(byteArrayOutputStream, TbOrderExport.class).registerConverter(new LongStringConverter()).sheet("淘宝订单").doWrite(tbOrderExportList);
                        ZipUtils.zip(out, new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), fileName);
                        byteArrayOutputStream.close();
                        //清空本次导出的数据列表
                        tbOrderExportList.clear();
                    }catch (Exception e){
                        if(byteArrayOutputStream != null){
                            try {
                                byteArrayOutputStream.close();
                            } catch (IOException ex) {
                                logger.error(e.getMessage(),e);
                            }
                        }
                        logger.error("----导出淘宝订单异常--error={}", e.getMessage());
                    }
                }
            }
            //循环查询下一页
            tbOrderQuery.setIdStart(idStart);
            tbOrderList = tbOrderMapper.findByList(page, tbOrderQuery);
        }

        //最后将剩余不足10000条的记录，生成excel文件
        if(tbOrderExportList.size() > 0){
            ByteArrayOutputStream byteArrayOutputStream = null;
            try {
                //导出的文件序号,每次导出+1
                exportFileNumber ++ ;
                String fileName = "淘宝订单_" + exportFileNumber +".xlsx";
                //创建流
                byteArrayOutputStream = new ByteArrayOutputStream();
                //打包成ZIP文件
                EasyExcel.write(byteArrayOutputStream, TbOrderExport.class).registerConverter(new LongStringConverter()).sheet("淘宝订单").doWrite(tbOrderExportList);
                ZipUtils.zip(out, new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), fileName);
                byteArrayOutputStream.close();
                //清空本次导出的数据列表
                tbOrderExportList.clear();
            }catch (Exception e){
                if(byteArrayOutputStream != null){
                    try {
                        byteArrayOutputStream.close();
                    } catch (IOException ex) {
                        logger.error(ex.getMessage(), ex);
                    }
                }
                logger.error("----导出淘宝订单异常--error={}", e.getMessage());
            }
        }

        try {
            // 注意关闭流的顺序，在上传oss之前必须关闭流否则下载解压的时候会报“文件末端错误”的问题
            outputStream.close();
            out.close();
        }catch (Exception e){
            logger.error("----上传淘宝订单关闭流异常--error={}", e.getMessage());
        }finally {

        }

        //上传文件到OSS当中
        InputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
        String zipFileName = "淘宝订单_" + System.currentTimeMillis() + ".zip";
        //上传文件通讯录
        exportInfoService.uploadExportFile(byteArrayInputStream, tbOrderExportResultDto.getMerId(), zipFileName, exportAmountVo, ExportInfoTypeEnum.EXPORT_INFO_TB_ORDER.getId());

    }

}
